package com.seadragon.app.dms.dao.jpa;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.seadragon.app.dms.dao.CustomerDao;
import com.seadragon.app.dms.model.Customer;

@Repository
public class CustomerDaoJpaImpl extends AbstractJpaDao implements CustomerDao {
	private static Logger logger = LoggerFactory.getLogger(CustomerDaoJpaImpl.class);
	@Override
	public void save(Customer customer) {
		entityManager.persist(customer);
	}

	@Override
	public void update(Customer customer) {
		entityManager.merge(customer);
		entityManager.flush();
	}

	@Override
	public Customer findByToken(String token) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);
		Root<Customer> root = cq.from(Customer.class);
		cq.select(root);
		cq.where(cb.equal(root.get("token"), token));
		List<Customer> customers = entityManager.createQuery(cq).getResultList();
		if(customers != null && customers.size() > 0){
			return customers.get(0);
		}
		return null;
	}
	
	@Override
	public Customer findByUserName(String userName) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);
		Root<Customer> root = cq.from(Customer.class);
		cq.select(root);
		cq.where(cb.equal(root.get("userName"), userName));
		Customer customer = null;
		try{
			customer = entityManager.createQuery(cq).getSingleResult();
		}catch(NoResultException ex){
			logger.info("This user doesn't exist in the database: " + userName);
		}
		return customer;
	}
}
